package com.oracle.application.aspect;

import com.oracle.application.mapper.auto.MonitorLogMapper;
import com.oracle.application.model.auto.MonitorLog;
import com.oracle.application.utils.CommonUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;


/**
 * @author lyz
 * @title: OperationAspect
 * @projectName springcloud
 * @date 2020/9/23
 * @description: 操作日志切面处理类
 */
@Aspect
@Component
public class OperationLogAspect {

    @Autowired(required = false)
    private MonitorLogMapper monitorLogMapper;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");

    @Pointcut("execution(* com.oracle.application.controller.*.*(..))")
    public void operLogPoinCut() {
    }

    @Around("operLogPoinCut()")
    public Object aroundMethod(ProceedingJoinPoint pjp){
        Object targetObj = null;
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        //监测路径
        String monitorpath = request.getRequestURL().toString();
        //调用时间
        LocalDateTime date = LocalDateTime.now();
        //方法执行耗时
        Long beginTime = System.currentTimeMillis();
        try {
            targetObj = pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        Long endTime = System.currentTimeMillis();
        String elapsedtime = (float) ((endTime-beginTime)/1000)+"";
        //调用方式
        String callmethod = request.getMethod();
        //登录ip
        String addressip = CommonUtil.getRealIP(request);
        //用户
        String username = callmethod;//因为数据库少些了请求方式字段，反正也没登录，直接写这儿得了
        MonitorLog monitorLog = new MonitorLog();
        monitorLog.setMonitorpath(monitorpath);
        monitorLog.setCalltime(date);
        monitorLog.setElapsedtime(elapsedtime);
        monitorLog.setAddressip(addressip);
        monitorLog.setUser(username);
        this.monitorLogMapper.insert(monitorLog);
        return targetObj;
    }


}